package com.bupt.ilink.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bupt.ilink.entity.User;
import com.bupt.ilink.entity.pojo.store.StoreFlowInfo;
//import com.bupt.ilink.entity.store.StoreFlowTeam;
import com.bupt.ilink.entity.userManagement.*;
import com.bupt.ilink.entity.userManagement.DTO.RoleStatistics;
import com.bupt.ilink.entity.userManagement.DTO.UserMetaResponse;
import com.bupt.ilink.entity.userManagement.DTO.UserTeamResponse;
//import com.bupt.ilink.mapper.StoreFlowTeamMapper;
import com.bupt.ilink.mapper.UserMapper;
import com.bupt.ilink.service.OssService;
import com.bupt.ilink.utils.R;
import com.bupt.ilink.mapper.StoreFlowMapper;
import com.bupt.ilink.mapper.StoreFlowTagMapper;
import com.bupt.ilink.mapper.userManagement.*;
import com.bupt.ilink.service.TeamService;
import com.bupt.ilink.utils.SnowflakeIdGenerator;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.validation.constraints.Null;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Value;
import javax.crypto.spec.SecretKeySpec;
@Service
@Transactional
public class TeamServiceImpl extends ServiceImpl<TeamMapper, UserTeam> implements TeamService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private TeamMapper TeamMapper;

    @Autowired
    private UserConnectTeamsMapper userConnectTeamsMapper;

    @Autowired
    private UserRolesMapper userRolesMapper;

    @Autowired
    private TeamGroupMapper teamGroupMapper;

    @Autowired
    private TeamFilesMapper teamFilesMapper;

    @Autowired
    private TeamSourceJurisdictionMapper teamSourceJurisdictionMapper;

    @Autowired
    private UserPermissionsMapper userPermissionsMapper;

    @Autowired
    private StoreFlowMapper storeFlowMapper;

    @Autowired
    private StoreFlowTagMapper storeFlowTagMapper;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private OssServiceImpl ossService;
    @Autowired
    private TeamMapper userTeamMapper;

    @Autowired
    private UserTeamPermissionsMapper userTeamPermissionsMapper;
    
    private static final String secretKey = "2024iLinkSecretKey2024";
    //创建日志记录类实例
    private static final Logger logger = LoggerFactory.getLogger(TeamServiceImpl.class);
    // @Autowired
    // private StoreFlowTeamMapper storeFlowTeamMapper;

    @Transactional
    @Override
    public Long CreateNewteam(String name, String teamType, String createdUser,String team_introduction) {
        // 1. 创建团队
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 3);
        Long id = idGenerator.nextId();
        UserTeam team = new UserTeam();
        team.setTeamId(id);
        team.setName(name);
//        team.setTeamType(teamType);
        team.setTeamType("团队");//统一团队
        team.setTeamNum(1);
        team.setCreatedUser(createdUser);
        team.setTeamIntroduction(team_introduction);
        boolean teamSaved = this.save(team);

        if (!teamSaved) {
            logger.error("创建团队，写入团队信息表失败");
            throw new RuntimeException("未能为团队写入信息");//用这种触发异常的方式，激发回退机制
        }

        // 2. 初始化队长，指导老师，管理员，队员 角色
        // 定义角色字典，包含角色名称及其特定的管理权限
        Map<String, Boolean[]> roleDict = new HashMap<>();
        roleDict.put("队长", new Boolean[]{true, true, true, true});//额外的解散团队的权力
        roleDict.put("指导老师", new Boolean[]{true, true, true, true});//额外的解散团队的权力
        roleDict.put("管理员", new Boolean[]{true, true, true, true});
        roleDict.put("队员", new Boolean[]{false, true, false,false});//成员管理 知识库管理 应用管理 数据集管理
        Long Roleid ;
        Long ConnectID= 0L;
        // 循环创建和插入角色
        for (Map.Entry<String, Boolean[]> entry : roleDict.entrySet()) {
            String roleName = entry.getKey();

            Boolean[] permissions = entry.getValue();
            Roleid=idGenerator.nextId();

            if (roleName.equals(teamType)) {
                ConnectID=Roleid;
            }
            // 创建UserRoles对象
            UserRoles userRoles = new UserRoles();
            userRoles.setRoleId(Roleid); // 多角色创建不再沿用之前的id
            userRoles.setRoleName(roleName); // 设置角色名称

            // 设置管理权限
            userRoles.setMemberManagement(permissions[0]);
            userRoles.setKnowledgeBaseManagement(permissions[1]);
            userRoles.setApplyManagement(permissions[2]);
            userRoles.setDatasetManagement(permissions[3]);

            userRoles.setTeamId(id); // 设置TeamId
            boolean roleInsert = userRolesMapper.insert(userRoles)>0; // 插入到数据库
            if (!roleInsert) {
                log.error("创建团队，写入角色信息表失败");
                throw new RuntimeException("未能为团队写入角色信息");
            }
        }

//        UserRoles userRoles=new UserRoles();
//        userRoles.setRoleId(id);//这里因为是不同的表沿用之前的id
////        if (teamType.equals("团队")) {
////            userRoles.setRoleName("队长");
////        }else {
////            userRoles.setRoleName("老师");
////        }
//        userRoles.setMemberManagement(true);
//        userRoles.setKnowledgeBaseManagement(true);
//        userRoles.setApplyManagement(true);
//        userRoles.setDatasetManagement(true);
//        userRoles.setTeamId(id);
//        userRolesMapper.insert(userRoles);
////        Long leaderRoleId = userRolesMapper.selectRoleIdByRoleNameandTeamId(role_name, teamId);
////        if (leaderRoleId == null) {
////            throw new RuntimeException("数据库中不存在默认队长角色,无法找到队长角色ID");
////        }

        // 3. 创建以团队名称为 name 的最高组别
        TeamGroup teamGroup = new TeamGroup();
        teamGroup.setGroupId(id);
        teamGroup.setName(name);
//        teamGroup.setParentId(null); // 最高组别，没有父级
//        teamGroup.setChildId(null);  // 没有子级，默认设置为 null
        boolean groupSaved = teamGroupMapper.insert(teamGroup) > 0;

        if (!groupSaved) {
            logger.error("为团队创建最高组别失败");
            throw new RuntimeException("未能为团队创建最高组别");
        }

        // 4. 插入用户-团队关系，设置当前用户为队长或指导老师
        UserConnectTeams userConnectTeams = new UserConnectTeams();
        userConnectTeams.setUserId(createdUser);
        userConnectTeams.setTeamId(team.getTeamId());
        userConnectTeams.setRoleId(ConnectID);
        userConnectTeams.setGroupId(teamGroup.getGroupId()); // 视需求而定
        boolean userConnect =userConnectTeamsMapper.insert(userConnectTeams) > 0;
        if (!userConnect) {
            logger.error("用户关联团队失败");
            throw new RuntimeException("未能用户关联团队");
        }

        //5.创建团队默认文件夹并进行关联,文件目前属于冗余设计，为后续知识库功能准备
        TeamFiles teamFiles=new TeamFiles();
        teamFiles.setTeamId(id);
        teamFiles.setGroupId(teamGroup.getGroupId());
        teamFiles.setFileName(name);
        teamFiles.setFileId(id);
        boolean teamFileADD=teamFilesMapper.insert(teamFiles)>0;
        if(!teamFileADD) {
            logger.error("团队文件夹初始失败");
            throw new RuntimeException("未能初始团队文件夹");
        }

        //6.更新团队关联文件夹 组别
        team.setCreatedUser(createdUser);
        team.setFileId(id);
        team.setGroupId(id);
        boolean teamUpdate=this.updateById(team);
        if(!teamUpdate) {
            logger.error("团队关联文件夹、组别失败");
            throw new RuntimeException("未能关联团队文件夹、组别");
        }
        return team.getTeamId();

    }




    //从团队中删除某用户
    @Transactional
    public boolean removeUserFromTeam(String userId, Long teamId) {
        // 从 user_connect_teams 表中删除指定的记录
        int rowsDeleted = userConnectTeamsMapper.deleteByUserIdInTeam(userId, teamId);

        // 如果删除成功，更新 User_team 表中的 team_num 字段
        if (rowsDeleted > 0) {
            boolean decremented = userTeamMapper.decrementTeamNum(teamId)>0;
            if (!decremented) {
                logger.error("更新团队成员数量失败");
                throw new RuntimeException("未能更新团队成员数量");
            }
            return true;
        }else {
            logger.error("从团队{}中删除{}用户失败", teamId, userId);
            throw new RuntimeException("未能从团队中删除用户");
//            return false;
        }
    }

    public List<UserTeamResponse> getTeamList(String userId) {
        // 1. 从 user_connect_teams 表获取用户所属的 team_id 列表
        List<UserConnectTeams> userTeams = userConnectTeamsMapper.selectList(
                new QueryWrapper<UserConnectTeams>().eq("user_id", userId)
        );

        List<UserTeamResponse> responses = new ArrayList<>();

        for (UserConnectTeams userTeam : userTeams) {
            // 2. 根据 team_id 获取团队信息
            UserTeam team = this.getById(userTeam.getTeamId());

            // 3. 根据 role_id 获取角色名称
            String roleName = userRolesMapper.selectById(userTeam.getRoleId()).getRoleName();

            // 4. 构建 UserTeamResponse 对象
            UserTeamResponse response = new UserTeamResponse();
            response.setTeamId(team.getTeamId());
            response.setName(team.getName());
            response.setRole_name(roleName);
            response.setTeam_num(team.getTeamNum());
            response.setTeam_type(team.getTeamType());

            // 5. 添加到响应列表
            responses.add(response);
        }
        return responses;
    }
    //用户自己创建的团队，有一个问题就是团队表外键关联用户表，与团队创建者绑定，那用户在注销之前需要解绑所有的团队先
    public List<UserTeamResponse> getTeamListCreatedByself(String userId) {
        // 1. 从 user_team 表获取创建者用户所属的 team_id 列表
        List<UserTeam> userTeams = userTeamMapper.selectList(
                new QueryWrapper<UserTeam>().eq("created_user", userId)
        );

        List<UserTeamResponse> responses = new ArrayList<>();

        for (UserTeam userTeam : userTeams) {
            // 2. 根据 team_id 获取团队信息
            UserTeam team = this.getById(userTeam.getTeamId());

            // 3. 根据 role_id 获取角色名称
//            String roleName = userRolesMapper.selectById(userTeam.getRoleId()).getRoleName();

            // 4. 构建 UserTeamResponse 对象
            UserTeamResponse response = new UserTeamResponse();
            response.setTeamId(team.getTeamId());
            response.setName(team.getName());
            response.setTeam_num(team.getTeamNum());
            response.setTeam_type(team.getTeamType());
            //这里做了默认处理，团队创建者默认这两种身份
            if (team.getTeamType().equals("团队")){
                response.setRole_name("队长");
            }else {
                response.setRole_name("老师");
            }

            // 5. 添加到响应列表
            responses.add(response);
        }
        return responses;
    }

    @Override
    public List<UserTeamResponse> getClassadd(String userId) {
        // 1. 从 user_connect_teams 表获取用户所属的 team_id 列表
        List<UserConnectTeams> userTeams = userConnectTeamsMapper.selectList(
                new QueryWrapper<UserConnectTeams>().eq("user_id", userId)
        );

        List<UserTeamResponse> responses = new ArrayList<>();

        for (UserConnectTeams userTeam : userTeams) {
            // 2. 根据 team_id 获取团队信息
            UserTeam team = this.getById(userTeam.getTeamId());
            if (team.getTeamType().equals("班级")){
                // 3. 根据 role_id 获取角色名称
                String roleName = userRolesMapper.selectById(userTeam.getRoleId()).getRoleName();

                // 4. 构建 UserTeamResponse 对象
                UserTeamResponse response = new UserTeamResponse();
                response.setTeamId(team.getTeamId());
                response.setName(team.getName());
                response.setRole_name(roleName);
                response.setTeam_num(team.getTeamNum());
                response.setTeam_type(team.getTeamType());

                // 5. 添加到响应列表
                responses.add(response);
            }

        }
        return responses;
    }
    //注销团队
    @Transactional
    public boolean removeTeam(UserTeam team) {
        //删除所关联应用
//        boolean deleteApp=storeFlowTeamMapper.delete(new QueryWrapper<StoreFlowTeam>().eq("team_id",team.getTeamId()))>0;
//        if (!deleteApp){
//            logger.error("团队{}的应用关联注销失败",team.getTeamId());
//            throw new RuntimeException("团队应用关联注销失败");
//        }
        //注销团队，确保user_roles user_team_permissions 都已ON DELETE CASCADE
        //注销用户关联，已与团队外键ON DELETE CASCADE，删除团队或用户即可
        boolean delete=this.removeById(team.getTeamId());
        if (!delete){
            logger.error("团队{}注销失败",team.getTeamId());
            throw new RuntimeException("团队注销失败");
        }

        //注销组别，确认组别team_group 自关联是 ON DELETE CASCADE
        boolean groupDelete=teamGroupMapper.deleteById(team.getGroupId())>0;
        if (!groupDelete){
            logger.error("组别{}注销失败",team.getGroupId());
            throw new RuntimeException("组别注销失败");
        }
        //注销文件夹，确认文件夹team_files未ON DELETE CASCADE，先删除
        boolean fileDelete=teamFilesMapper.deleteById(team.getFileId())>0;
        if (!fileDelete){
            logger.error("文件夹{}注销失败",team.getFileId());
            throw new RuntimeException("文件夹注销失败");
        }

        return true;

    }


    public boolean quitTeam(String userId, Long teamId) {
        //判断用户是否是团队创建者
        UserTeam team=userTeamMapper.selectOne(new QueryWrapper<UserTeam>().eq("team_id",teamId));
        if (team==null){
            return false;
        }
        if (team.getCreatedUser().equals(userId)){
            //判断该团队是否还有其他成员，如果有，则不能退出
            List<UserConnectTeams> userConnectTeams=userConnectTeamsMapper.selectList(new QueryWrapper<UserConnectTeams>().eq("team_id",teamId));
            if (userConnectTeams.size()>1){
                throw new RuntimeException("该团队还有其他成员，不能退出,请先转移");
            }else{
                //注销团队
                return removeTeam(team);
            }
        }else {
            //删除用户从团队中
            return removeUserFromTeam(userId, teamId);
//            return userConnectTeamsMapper.deleteByUserIdInTeam(userId, teamId)>0;

        }
    }

    //获取用户于本项目可见的全部应用
    public Map<String, List<StoreFlowInfo>> getTeamResourcesApply(String userId, Long teamId,String keyword) {

        // 1. 获取用户的 group_id
        Long groupId = userConnectTeamsMapper.selectGroupIdByUserIdAndTeamId(userId, teamId);
        if (groupId == null) {
            throw new RuntimeException("无法找到用户的组别，用户团队数据存疑");
        }

//        // 2. 获取 Applymanagement 权限
//        Boolean hasApplymanagement = userPermissionsMapper.checkUserPermission(userId, teamId, "Applymanagement");
        // 3. 递归获取文件夹和资源
        Map<String, List<StoreFlowInfo>> result = new HashMap<>();
//        recurseFiles(groupId, result, userId, teamId);
        //groupId teamId从表team_files中获取分组下的对应文件file_id 和 file_name  //！递归的获取对应的子文件那些和资源
        List<TeamFiles> files = teamFilesMapper.selectByGroupSource(groupId,teamId);
        for (TeamFiles file : files){
            String fileName = file.getFileName();
            Long fileId = file.getFileId();

            // 查询对应file_id下的source_flow_id，当source_type为'应用'时
            List<String> sourceFlowIds = teamSourceJurisdictionMapper.selectSourceFlowIdByFileIdAndType(fileId, "应用");

            // 根据sourceFlowId获取StoreFlow信息
            List<StoreFlowInfo> storeFlowInfos = new ArrayList<>();
            for (String sourceFlowId : sourceFlowIds) {
                // 检查用户权限  检查 source_flow_id 对应的用户权限
                Boolean hasPermission = userPermissionsMapper.checkSourceAuthority(userId, teamId, sourceFlowId);

                if (Boolean.TRUE.equals(hasPermission) || hasPermission == null){
                    StoreFlowInfo storeFlowInfoadd = storeFlowMapper.getStoreFlowInfosBySourceFlowId(sourceFlowId);
                    List<String> Tags = storeFlowTagMapper.getTagsByflowId(storeFlowInfoadd.getFlowId());
                    storeFlowInfoadd.setTagsNames(Tags);
                    storeFlowInfos.add(storeFlowInfoadd);
                }
            }
            //使用流操作对列表属性以字符串做筛选
            if (keyword != null && !keyword.isEmpty()) {
                storeFlowInfos = storeFlowInfos.stream()
                        .filter(storeFlowInfo -> storeFlowInfo.getTagsNames().stream()
                                .anyMatch(tag -> tag.contains(keyword)))
                        .collect(Collectors.toList());
            }

            // 将获取的StoreFlowInfo列表添加到Map中
            result.put(fileName, storeFlowInfos);
        }

        //从team_source_jurisdiction中获取对应的source_flow_id然后获取相关Meta
        //对查到的结果进行User_permissions查找，如果有对应的行以其上的规则为准

        // 4. 返回结果和权限
        return result;
    }
    //递归查询的代码，现在只有知识库有层级文件夹，到时候使用本函数修改
//    private void recurseFiles(Long groupId, Map<String, List<StoreFlowInfo>> result, String userId, Long teamId) {
//        List<TeamFiles> files = teamFilesMapper.selectByGroupSource(groupId,teamId);
//        for (TeamFiles file : files) {
//            List<TeamSourceJurisdiction> sources = teamSourceJurisdictionMapper.selectByFileId(file.getFileId());
//            for (TeamSourceJurisdiction source : sources) {
//                if (source.getSourceType().equals("文件夹")) {
//                    // 递归查询子文件夹
//                    recurseFiles(source.getChildId(), result, userId, teamId);
//                } else {
//                    // 检查用户权限  检查 source_flow_id 对应的用户权限
//                    Boolean hasPermission = userPermissionsMapper.checkSourceAuthority(userId, teamId, source.getSourceFlowId());
//                    if (hasPermission != null && hasPermission) {
//                        StoreFlowInfo storeFlowInfo = new StoreFlowInfo();
//                        //待放入
//
//                        result.computeIfAbsent(file.getFileName(), k -> new ArrayList<>()).add(storeFlowInfo);
//                    }
//                }
//            }
//        }
//    }
    //获取用户对应管理权限
    public boolean getUserTeamManagement(String userId,Long teamId) {
        //获取用户在团队内的管理权限
        Boolean hasMemberManagement = userConnectTeamsMapper.getMemberManagementByUserIdAndTeamId(userId, teamId);
        UserTeamPermissions userTeamPermissions = userTeamPermissionsMapper.selectOne(new QueryWrapper<UserTeamPermissions>().eq("team_id", teamId).eq("user_id", userId));
        //同时确认个人的管理权限
        if (hasMemberManagement==null){
            hasMemberManagement=false;
        }
        //如果有个人管理权限
        if (userTeamPermissions!=null){
            hasMemberManagement=hasMemberManagement || userTeamPermissions.getMemberManagement();
        }
        return hasMemberManagement;
    }

    public Map<String,Object>  getTeamMembers(String userId, Long teamId, Long groupId, int pageNum, int pageSize, String realnameFilter) {
        Map<String,Object> result=new HashMap<>();

        //根据用户在团队内的角色权限决定返回什么
        List<UserMetaResponse> responses = new ArrayList<>();
        Boolean hasMemberManagement = userConnectTeamsMapper.getMemberManagementByUserIdAndTeamId(userId, teamId);
        UserTeamPermissions userTeamPermissions = userTeamPermissionsMapper.selectOne(new QueryWrapper<UserTeamPermissions>().eq("team_id", teamId).eq("user_id", userId));
        //同时确认个人的管理权限
        if (hasMemberManagement==null){
            hasMemberManagement=false;
        }
        //如果有个人管理权限
        if (userTeamPermissions!=null){
            hasMemberManagement=hasMemberManagement || userTeamPermissions.getMemberManagement();
        }

        if ( hasMemberManagement) {
            // 用户具有成员管理权限
            // 递归获取所有下级group并获取对应用户信息
            getGroupMembersRecursively(groupId, teamId, responses);

        } else {
            // 用户没有成员管理权限
            getGroupMembersBasic(groupId, teamId, responses);
        }
//        return responses;
        // 过滤操作：对所有结果中的 realname 进行模糊查询
        if (realnameFilter != null && !realnameFilter.isEmpty()) {
            responses = responses.stream()
                    .filter(userMeta -> userMeta.getRealName() != null && userMeta.getRealName().contains(realnameFilter))
                    .collect(Collectors.toList());
        }
        // 分页处理
        Page<UserMetaResponse> page = new Page<>(pageNum, pageSize);
        int total = responses.size();
        int start = (int) ((page.getCurrent() - 1) * page.getSize());
        int end = Math.min(start + (int) page.getSize(), total);
        List<UserMetaResponse> paginatedList = responses.subList(start, end);
        page.setRecords(paginatedList);
        page.setTotal(total);

        result.put("userMessage",page);
        result.put("memberManagement",hasMemberManagement);

        return result;
    }

    private void getGroupMembersRecursively(Long groupId, Long teamId, List<UserMetaResponse> userMetaResponses) {
        // 获取当前group下的所有用户
        List<UserMetaResponse> groupMembers = userConnectTeamsMapper.getGroupMembersByTeamIdAndGroupId(teamId, groupId);
        userMetaResponses.addAll(groupMembers);
        // 递归获取下级group的信息
        List<TeamGroup> childGroups = teamGroupMapper.findChildGroupsByParentId(groupId);
        for (TeamGroup childGroup : childGroups) {
            getGroupMembersRecursively(childGroup.getGroupId(), teamId, userMetaResponses);
        }
    }
    private void  getGroupMembersBasic(Long groupId, Long teamId, List<UserMetaResponse> userMetaResponses) {
        // 获取当前group下的所有用户
        List<UserMetaResponse> groupMembers = userConnectTeamsMapper.getGroupMembersBasicByTeamIdAndGroupId(teamId, groupId);
        userMetaResponses.addAll(groupMembers);
        // 递归获取下级group的信息
        List<TeamGroup> childGroups = teamGroupMapper.findChildGroupsByParentId(groupId);
        for (TeamGroup childGroup : childGroups) {
            getGroupMembersRecursively(childGroup.getGroupId(), teamId, userMetaResponses);
        }
    }

    public R getTeamDepartment(String userId, Long teamId) {
        // Step 1: 获取用户在团队中的 group_id
        UserConnectTeams userConnectTeams = userConnectTeamsMapper.findUsermessageByUserIdAndTeamId(userId, teamId);

        if ( userConnectTeams.getGroupId() == null) {
            logger.error("用户{}于团队{}中所属组别未知",userId,teamId);
            return R.failure("用户没有所属组， 疑似团队数据有问题");
        }
        // Step 2: 递归构建树状结构
        return R.ok(buildGroupHierarchy(teamGroupMapper.selectById(userConnectTeams.getGroupId())));
    }
    private JsonNode buildGroupHierarchy(TeamGroup group) {
        // Step 3: 获取当前 group 的信息
        if (group == null) {
            return null;
        }
        // Step 4: 创建 JSON 节点
        ObjectNode jsonNode = objectMapper.createObjectNode();
        jsonNode.put("groupId", group.getGroupId());
        jsonNode.put("name", group.getName());

        // Step 5: 获取子组列表并递归
        List<TeamGroup> ChildGroups=teamGroupMapper.findChildGroupsByParentId(group.getGroupId());
        for (TeamGroup ChildGroup:ChildGroups){
            jsonNode.set("child", buildGroupHierarchy(ChildGroup));
        }

        return jsonNode;
    }

    public List<RoleStatistics> getRoleStatisticsByTeamId(Long teamId) {
        return userConnectTeamsMapper.getRoleStatisticsByTeamId(teamId);
    }

    public List<TeamFiles> getTeamResourcesFiles(String userId, Long teamId) {
        // 添加业务逻辑,检查用户是否有权限访问该团队的资源文件

        // 查询数据库，获取该团队的资源文件列表

        return teamFilesMapper.getTeamResourcesFiles(userId, teamId);

    }

    public List<StoreFlowInfo> getTeamApplyResources(String userId, Long fileId, Long teamId, String keyword) {
        // 查询对应file_id下的source_flow_id，当source_type为'应用'时
        List<String> sourceFlowIds = teamSourceJurisdictionMapper.selectSourceFlowIdByFileIdAndType(fileId, "应用");

        // 根据sourceFlowId获取StoreFlow信息
        List<StoreFlowInfo> storeFlowInfos = new ArrayList<>();
        for (String sourceFlowId : sourceFlowIds) {
            // 检查用户权限  检查 source_flow_id 对应的用户权限
            Boolean hasPermission = userPermissionsMapper.checkSourceAuthority(userId, teamId, sourceFlowId);

            if (Boolean.TRUE.equals(hasPermission) || hasPermission == null) {
                StoreFlowInfo storeFlowInfoadd = storeFlowMapper.getStoreFlowInfosBySourceFlowId(sourceFlowId);
                List<String> Tags = storeFlowTagMapper.getTagsByflowId(storeFlowInfoadd.getFlowId());
                storeFlowInfoadd.setTagsNames(Tags);
                storeFlowInfos.add(storeFlowInfoadd);
            }
        }
        //使用流操作对列表属性以字符串做筛选
        if (keyword != null && !keyword.isEmpty()) {
            storeFlowInfos = storeFlowInfos.stream()
                    .filter(storeFlowInfo -> storeFlowInfo.getTagsNames().stream()
                            .anyMatch(tag -> tag.contains(keyword)))
                    .collect(Collectors.toList());
        }
        return storeFlowInfos;

    }

    public List<UserMetaResponse> getRoleMessage(Long teamId) {
        return userConnectTeamsMapper.getRoleMessage(teamId);

    }

    public JsonNode getRoleStatisticsMessage(Long teamId, List<RoleStatistics> teamRoles) {
        ObjectNode jsonNode = objectMapper.createObjectNode();
        for (RoleStatistics roleStatistics : teamRoles){
            ObjectNode childjsonNode = objectMapper.createObjectNode();
            childjsonNode.put("roleId",roleStatistics.getRoleId());
            childjsonNode.put("roleCount",roleStatistics.getRoleCount());
            childjsonNode.set("usersIamge", userConnectTeamsMapper.getUserMessageByRole(roleStatistics.getRoleId()));
            jsonNode.set(roleStatistics.getRoleName(),childjsonNode);
        }
        return jsonNode;

    }

    //批量添加用户到团队
    public boolean addTeamMembers( Long teamId, List<String> userIds){
        //根据用户名获取用户的数据库id
        List<String> user_ids = new ArrayList<>();
        for (String userId : userIds){
            String user_id = userMapper.findUserIdByUsername(userId);
            if (user_id == null) {
                throw new RuntimeException("用户" + userId + "不存在");
            }
            user_ids.add(user_id);
        }
        // 1. 获取小组的 group_id
        Long groupId = userTeamMapper.findGroupIdByTeamId(teamId);
        if (groupId == null) {
            throw new RuntimeException("无法找到用户的组别，用户团队数据存疑");
        }
        // 2. 初始化roleId
        //如果是团队，那么默认角色是队员，如果是班级，那么默认角色是学生
        String teamType = userTeamMapper.findTeamTypeByTeamId(teamId);
        Long roleId = null;
        if (teamType.equals("团队")) {
            roleId = userRolesMapper.selectRoleIdByRoleNameandTeamId("队员", teamId);
            if (roleId == null) {
                SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 3);
                Long id = idGenerator.nextId();
                UserRoles userRoles = new UserRoles();
                userRoles.setRoleId(id);//这里因为是不同的表沿用之前的id
                userRoles.setRoleName("队员");
                userRoles.setMemberManagement(false);
                userRoles.setKnowledgeBaseManagement(false);
                userRoles.setApplyManagement(false);
                userRoles.setDatasetManagement(false);
                userRoles.setTeamId(teamId);
                userRolesMapper.insert(userRoles);
                roleId = id;
            }
        } else if (teamType.equals("班级")) {
            roleId = userRolesMapper.selectRoleIdByRoleNameandTeamId("学生", teamId);
            if (roleId == null) {
                SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 3);
                Long id = idGenerator.nextId();
                UserRoles userRoles = new UserRoles();
                userRoles.setRoleId(id);//这里因为是不同的表沿用之前的id
                userRoles.setRoleName("学生");
                userRoles.setMemberManagement(false);
                userRoles.setKnowledgeBaseManagement(false);
                userRoles.setApplyManagement(false);
                userRoles.setDatasetManagement(false);
                userRoles.setTeamId(teamId);
                userRolesMapper.insert(userRoles);
                roleId = id;
            }

        }
        boolean userConnect = true;
        // 3. 批量添加用户
        for (String user : user_ids) {
            //判断用户是否已经在团队中
            UserConnectTeams userConnectTeams = userConnectTeamsMapper.findUsermessageByUserIdAndTeamId(user, teamId);
            if (userConnectTeams != null) {
                logger.error("用户{}已经在团队{}中",user,teamId);
                continue;
            }
            userConnectTeams = new UserConnectTeams();
            //判断用户是否存在
            User user1 = userMapper.selectById(user);
            userConnectTeams.setUserId(user);
            userConnectTeams.setTeamId(teamId);
            userConnectTeams.setRoleId(roleId);
            userConnectTeams.setGroupId(groupId); // 视需求而定
            userConnect =userConnectTeamsMapper.insert(userConnectTeams) > 0;
            if (!userConnect) {
                logger.error("用户关联团队失败");
                throw new RuntimeException("未能用户关联团队");
            }
            //更新团队成员数量
            boolean incremented = userTeamMapper.addTeamNum(teamId)>0;
            if (!incremented) {
                logger.error("更新团队成员数量失败");
                throw new RuntimeException("未能更新团队成员数量");
            }
        }
        return userConnect;
    }

    //查询邀请码
    public String getInvitationCode(Long teamId) {
        UserTeam userTeam = userTeamMapper.selectById(teamId);
        return userTeam.getInvitationCode();
    }

    //团队生成邀请码
    public String generateInvitationCode(Long teamId) {
        try {
            // 1. Combine teamId and current timestamp
            String data = teamId + ":" + System.currentTimeMillis();
            byte[] decodedKey = Base64.getDecoder().decode(secretKey);
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
            byte[] encryptedData = cipher.doFinal(data.getBytes());

            // 3. Encode the encrypted data to Base64
            String encryptedString = Base64.getEncoder().encodeToString(encryptedData);

            // 4. Save the encrypted invitation code
            UserTeam userTeam = userTeamMapper.selectById(teamId);
            userTeam.setInvitationCode(encryptedString);
            userTeamMapper.updateById(userTeam);
            return encryptedString;
        } catch (Exception e) {
            logger.error("生成邀请码失败");
            e.printStackTrace();
            throw new RuntimeException("Error generating invitation code", e);
        }
    }

    //团队邀请码有效期验证
    public boolean isInvitationCodeValid(String invitationCode) {
        try {
            // 1. Decode the Base64 encoded string
            byte[] decodedData = Base64.getDecoder().decode(invitationCode);
            byte[] decodedKey = Base64.getDecoder().decode(secretKey);
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedData = cipher.doFinal(decodedData);

            // 3. Extract the teamId and timestamp
            String decryptedString = new String(decryptedData);
            String[] parts = decryptedString.split(":");
            Long teamId = Long.parseLong(parts[0]);
            if (teamId == null) {
                return false;
            }
            UserTeam userTeam = userTeamMapper.selectById(teamId);
            if (userTeam == null) {
                logger.error("团队{}不存在",teamId);
                return false;
            }
            if (!invitationCode.equals(userTeam.getInvitationCode())) {
                return false;
            }
            logger.info("teamId: {}, teamName: {}", teamId, userTeam.getName());
            long timestamp = Long.parseLong(parts[1]);

            // 4. Check if the timestamp is within the last 7 days
            long currentTime = System.currentTimeMillis();
            long sevenDaysInMillis = 7 * 24 * 60 * 60 * 1000L;
            logger.info("currentTime: {}, timestamp: {}, diff: {}", currentTime, timestamp, currentTime - timestamp);
            return (currentTime - timestamp) <= sevenDaysInMillis;
        } catch (Exception e) {
            return false;
        }
    }

    //根据邀请码加入团队
    public boolean joinTeamByInvitationCode(String userId, String invitationCode) {
        try {
            // Check if the invitation code is valid
            if (!isInvitationCodeValid(invitationCode)) {
                throw new RuntimeException("邀请码失效");
            }
            // 1. Decode the Base64 encoded string
            byte[] decodedData = Base64.getDecoder().decode(invitationCode);

            // 2. Decrypt the data
            byte[] decodedKey = Base64.getDecoder().decode(secretKey);
            SecretKeySpec secretKeySpec = new SecretKeySpec(decodedKey, 0, decodedKey.length, "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
            byte[] decryptedData = cipher.doFinal(decodedData);

            // 3. Extract the teamId and timestamp
            String decryptedString = new String(decryptedData);
            String[] parts = decryptedString.split(":");
            Long teamId = Long.parseLong(parts[0]);
            // 4. Add the user to the team
            String userid = userMapper.findUserIdByUsername(userId);
            UserConnectTeams userConnectTeams = userConnectTeamsMapper.findUsermessageByUserIdAndTeamId(userid, teamId);
            if (userConnectTeams != null) {
                throw new RuntimeException("用户已经在团队中");
            }
            userConnectTeams = new UserConnectTeams();
            //判断用户是否存在
            User user1 = userMapper.selectById(userid);
            if (user1 == null) {
                throw new RuntimeException("用户不存在");
            }
            // 1. 获取小组的 group_id
            Long groupId = userTeamMapper.findGroupIdByTeamId(teamId);
            if (groupId == null) {
                throw new RuntimeException("无法找到用户的组别，用户团队数据存疑");
            }
            //roleId
            //如果是团队，那么默认角色是队员，如果是班级，那么默认角色是学生
            String teamType = userTeamMapper.findTeamTypeByTeamId(teamId);
            Long roleId = null;
            if (teamType.equals("团队")) {
                roleId = userRolesMapper.selectRoleIdByRoleNameandTeamId("队员", teamId);
                if (roleId == null) {
                    SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 3);
                    Long id = idGenerator.nextId();
                    UserRoles userRoles = new UserRoles();
                    userRoles.setRoleId(id);//这里因为是不同的表沿用之前的id
                    userRoles.setRoleName("队员");
                    userRoles.setMemberManagement(false);
                    userRoles.setKnowledgeBaseManagement(false);
                    userRoles.setApplyManagement(false);
                    userRoles.setDatasetManagement(false);
                    userRoles.setTeamId(teamId);
                    userRolesMapper.insert(userRoles);
                    roleId = id;
                }
            } else if (teamType.equals("班级")) {
                roleId = userRolesMapper.selectRoleIdByRoleNameandTeamId("学生", teamId);
                if (roleId == null) {
                    SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 3);
                    Long id = idGenerator.nextId();
                    UserRoles userRoles = new UserRoles();
                    userRoles.setRoleId(id);//这里因为是不同的表沿用之前的id
                    userRoles.setRoleName("学生");
                    userRoles.setMemberManagement(false);
                    userRoles.setKnowledgeBaseManagement(false);
                    userRoles.setApplyManagement(false);
                    userRoles.setDatasetManagement(false);
                    userRoles.setTeamId(teamId);
                    userRolesMapper.insert(userRoles);
                    roleId = id;
                }
            }

            userConnectTeams.setUserId(userid);
            userConnectTeams.setTeamId(teamId);
            userConnectTeams.setRoleId(roleId);
            userConnectTeams.setGroupId(groupId); // 视需求而定
            boolean userConnect =userConnectTeamsMapper.insert(userConnectTeams) > 0;
            if (!userConnect) {
                logger.error("用户关联团队失败");
                throw new RuntimeException("未能用户关联团队");
            }
            //更新团队成员数量
            boolean incremented = userTeamMapper.addTeamNum(teamId)>0;
            if (!incremented) {
                logger.error("更新团队成员数量失败");
                throw new RuntimeException("未能更新团队成员数量");
            }
            return userConnect;
        } catch (Exception e) {
            logger.error("加入团队失败");
            e.printStackTrace();
            return false;

        }
    }

    public boolean addTeamRole(UserRoles userRoles) {
        SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(3, 1);
        Long id = idGenerator.nextId();
        userRoles.setRoleId(id);
        return userRolesMapper.insert(userRoles) > 0;
    }


    public List<UserRoles> getTeamRoles(Long teamId) {
        return userRolesMapper.selectList(new QueryWrapper<UserRoles>().eq("team_id",teamId));
    }


    @Transactional
    public boolean setUserRole(Long teamId, List<String> userIds, Long roleId) {
        for (String userId : userIds){
//            boolean update = userConnectTeamsMapper.setUserRole(teamId,userId,roleId);
//            if (!update) {
//                logger.error("用户{}在团队{}中角色修改失败",userId,teamId);
//                throw new RuntimeException("未能修改用户角色");
//            }
            UserConnectTeams userConnectTeams = userConnectTeamsMapper.findUsermessageByUserIdAndTeamId(userId, teamId);
            if (userConnectTeams == null) {
                logger.error("用户{}不在团队{}中",userId,teamId);
//                throw new RuntimeException("用户不在团队中");
            }else{
                userConnectTeams.setRoleId(roleId);
                logger.info("修改用户{}在团队{}的角色为{}",userId,teamId,roleId);
                LambdaQueryWrapper<UserConnectTeams> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq( UserConnectTeams::getUserId,userId).eq(UserConnectTeams::getTeamId,teamId);
                boolean update =userConnectTeamsMapper.update(userConnectTeams,queryWrapper)>0;
//                boolean update =userConnectTeamsMapper.u
                if (!update) {
                    logger.error("用户{}在团队{}中角色修改失败",userId,teamId);
                    throw new RuntimeException("未能修改用户角色");
                }
            }
        }
        return true;
//        return userConnectTeamsMapper.setUserRole(teamId,userIds,roleId);
    }

    @Transactional
    public boolean setUserResourceRole(Long teamId, List<String> userIds,UserTeamPermissions userTeamPermissionsadd) {
        for (String userId : userIds){
            //userTeamPermissionsadd换成当前用户的
            UserTeamPermissions userTeamPermissions = userTeamPermissionsMapper.selectOne(new QueryWrapper<UserTeamPermissions>().eq("team_id", teamId).eq("user_id", userId));
            if (userTeamPermissions == null) {
                userTeamPermissionsadd.setTeamId(teamId);
                userTeamPermissionsadd.setUserId(userId);
                logger.info("添加用户{}资源权限",userId);
                boolean insert =userTeamPermissionsMapper.insert(userTeamPermissionsadd)>0;
                if (!insert) {
                    logger.error("添加用户{}资源权限失败",userId);
                    throw new RuntimeException("未能为用户添加权限");
                }

            }else {//已经有资源这是替换
                userTeamPermissionsadd.setTeamId(teamId);
                userTeamPermissionsadd.setUserId(userId);
                logger.info("替换用户{}资源权限",userId);
                logger.info("用户信息：{}",userTeamPermissionsadd);
                boolean update =userTeamPermissionsMapper.update(userTeamPermissionsadd,new QueryWrapper<UserTeamPermissions>().eq("team_id", teamId).eq("user_id", userId)) > 0;
                if (!update) {
                    logger.error("更新用户{}资源权限失败",userId);
                    throw new RuntimeException("未能为用户更新权限");
                }
            }

        }
        return true;
    }

    public boolean judgeAdmin(String userId, Long teamId) {
        System.out.println(teamId);
        String roleName = userConnectTeamsMapper.getRoleNameByUserIdAndTeamId(userId, teamId);
        if (roleName == null){
            return false;
        }
        return roleName.equals("队长") || roleName.equals("指导老师");
    }

    public Map<String, String> getTeamInfo(Long teamId, boolean isAdmin) {
        UserTeam userTeam = userTeamMapper.selectById(teamId);
        if (userTeam == null){
            return null;
        }
        String adminId = userTeam.getCreatedUser();
        User admin = userMapper.selectById(adminId);
        Map<String, String> teamInfo = new HashMap<>();
        teamInfo.put("teamName", userTeam.getName());
        teamInfo.put("teamIntroduction", userTeam.getTeamIntroduction());
        teamInfo.put("adminName", admin.getNickname());
        if (admin.getUserImage() != null){
            String ImageUrl = ossService.getFileUrl(admin.getUserImage());
            if (ImageUrl != null){
                teamInfo.put("adminImage", ImageUrl);
            }
            else{
                log.error(adminId + "用户头像获取失败");
            }
        }
        if (isAdmin){
            teamInfo.put("invitationCode", userTeam.getInvitationCode());
        }
        return teamInfo;
    }

    public boolean updateTeamInfo(Long teamId, JsonNode teamInfo){
        UserTeam userTeam = userTeamMapper.selectById(teamId);
        if (userTeam == null){
            return false;
        }
        System.out.println(userTeam.getName());
        if (teamInfo.has("teamName")){
            System.out.println(teamInfo.get("teamName").asText());
            userTeam.setName(teamInfo.get("teamName").asText());
        }
        if (teamInfo.has("teamIntroduction")){
            System.out.println(teamInfo.get("teamIntroduction").asText());
            userTeam.setTeamIntroduction(teamInfo.get("teamIntroduction").asText());
        }
        if (teamInfo.has("invitationCode")){
            userTeam.setInvitationCode(teamInfo.get("invitationCode").asText());
        }
        return userTeamMapper.updateById(userTeam) > 0;
    }
}
